package com.zhaoqi.hr.controller;

import com.zhaoqi.hr.dto.request.AdminUserCreateRequest;
import com.zhaoqi.hr.dto.request.JobPostingRequest;
import com.zhaoqi.hr.dto.response.ApiResponse;
import com.zhaoqi.hr.dto.response.ContractResponse;
import com.zhaoqi.hr.dto.response.UserOptionResponse;
import com.zhaoqi.hr.dto.response.UserResponse;
import com.zhaoqi.hr.dto.response.EmployerProfileResponse;
import com.zhaoqi.hr.dto.request.EmployerAuditRequest;
import com.zhaoqi.hr.dto.request.EmployerCreateRequest;
import com.zhaoqi.hr.dto.response.*;
import com.zhaoqi.hr.entity.User;
import com.zhaoqi.hr.entity.WorkContract;
import com.zhaoqi.hr.entity.WorkerProfile;
import com.zhaoqi.hr.repository.WorkerProfileRepository;
import com.zhaoqi.hr.security.CurrentUser;
import com.zhaoqi.hr.security.UserPrincipal;
import com.zhaoqi.hr.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;

/**
 * 管理员控制器
 */
@RestController
@RequestMapping("/admin")
@PreAuthorize("hasRole('ADMIN')")
public class AdminController {

    private static final Logger log = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private DocumentService documentService;

    @Autowired
    private EmployerProfileService employerProfileService;

    @Autowired
    private JobService jobService;

    @Autowired
    private ContractService contractService;
    
    @Autowired
    private WorkerProfileService workerProfileService;
    
    @Autowired
    private WorkerProfileRepository workerProfileRepository;

    /**
     * 获取平台统计数据
     */
    @GetMapping("/dashboard/stats")
    public ApiResponse<Map<String, Object>> getDashboardStats() {
        Map<String, Object> stats = userService.getPlatformStatistics();
        return ApiResponse.success("", stats);
    }

    /**
     * 获取用户列表
     */
    @GetMapping("/users")
    public ApiResponse<Page<User>> getUsers(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) User.UserRole role,
            @RequestParam(required = false) User.UserStatus status) {
        
        Pageable pageable = PageRequest.of(page, size);
        Page<User> users = userService.getUsers(pageable, role, status);
        return ApiResponse.success("", users);
    }

    /**
     * 创建新用户
     */
    @PostMapping("/users")
    public ApiResponse<User> createUser(@RequestBody AdminUserCreateRequest request) {
        User user = userService.createUserByAdmin(request);
        return ApiResponse.success("用户创建成功", user);
    }

    /**
     * 更新用户状态
     */
    @PutMapping("/users/{userId}/status")
    public ApiResponse<Void> updateUserStatus(
            @PathVariable Long userId,
            @RequestParam User.UserStatus status,
            @RequestParam(required = false) String reason) {
        
        userService.updateUserStatus(userId, status, reason);
        return ApiResponse.success("用户状态更新成功", null);
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/users/{userId}")
    public ApiResponse<Void> deleteUser(@PathVariable Long userId) {
        userService.deleteUser(userId);
        return ApiResponse.success("用户删除成功", null);
    }
    
    /**
     * 管理员创建文档
     */
    @PostMapping("/documents")
    public ApiResponse<DocumentResponse> createDocument(@RequestBody Map<String, Object> request) {
        DocumentResponse document = documentService.createDocumentByAdmin(request);
        return ApiResponse.success("文档创建成功", document);
    }
    
    /**
     * 获取用户列表（用于下拉选择）
     */
    @GetMapping("/users/options")
    public ApiResponse<List<UserOptionResponse>> getUserOptions(
            @RequestParam(required = false) String search,
            @RequestParam(defaultValue = "10") int limit) {
        List<UserOptionResponse> users = userService.getUserOptions(search, limit);
        return ApiResponse.success("", users);
    }

    /**
     * 获取待审核文档列表
     */
    @GetMapping("/documents/pending")
    public ApiResponse<List<DocumentResponse>> getPendingDocuments() {
        List<DocumentResponse> documents = documentService.getPendingAuditDocuments();
        return ApiResponse.success("", documents);
    }

    /**
     * 批量审核文档
     */
    @PostMapping("/documents/batch-audit")
    public ApiResponse<Void> batchAuditDocuments(
            @RequestBody List<Long> documentIds,
            @RequestParam String auditStatus,
            @RequestParam(required = false) String auditComment) {
        
        documentService.batchAuditDocuments(documentIds, auditStatus, auditComment);
        return ApiResponse.success("批量审核完成", null);
    }

    /**
     * 获取用工方列表
     */
    @GetMapping("/employers")
    public ApiResponse<Page<EmployerProfileResponse>> getEmployers(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String status) {
        
        Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());
        Page<EmployerProfileResponse> employers = employerProfileService.getEmployersForAdmin(pageable, status);
        return ApiResponse.success("", employers);
    }

    /**
     * 审核用工方资质
     */
    @PutMapping("/employers/{id}/audit")
    public ApiResponse<String> auditEmployer(@PathVariable Long id, @Valid @RequestBody EmployerAuditRequest request) {
        try {
            employerProfileService.auditEmployer(id, request);
            return ApiResponse.success("审核成功", "审核成功");
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 创建用工方（管理员代创建）
     */
    @PostMapping("/employers")
    public ApiResponse<EmployerProfileResponse> createEmployer(@Valid @RequestBody EmployerCreateRequest request) {
        try {
            EmployerProfileResponse response = employerProfileService.createEmployer(request);
            return ApiResponse.success("用工方创建成功", response);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 创建新岗位
     */
    @PostMapping("/jobs")
    public ApiResponse<JobPostingResponse> createJob(@RequestBody JobPostingRequest request) {
        JobPostingResponse job = jobService.createJobByAdmin(request);
        return ApiResponse.success("岗位创建成功", job);
    }

    /**
     * 获取岗位管理列表
     */
    @GetMapping("/jobs")
    public ApiResponse<Page<JobPostingResponse>> getJobPostings(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String keyword) {
        
        Pageable pageable = PageRequest.of(page, size);
        Page<JobPostingResponse> jobs = jobService.getJobPostingsForAdmin(pageable, status, keyword);
        return ApiResponse.success("", jobs);
    }

    /**
     * 获取岗位申请管理列表
     */
    @GetMapping("/job-applications")
    public ApiResponse<Page<JobApplicationResponse>> getJobApplications(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String status) {
        
        Pageable pageable = PageRequest.of(page, size);
        Page<JobApplicationResponse> applications = jobService.getJobApplicationsForAdmin(pageable, status);
        return ApiResponse.success("", applications);
    }

    /**
     * 人工撮合岗位和劳动者
     */
    @PostMapping("/jobs/{jobId}/match")
    public ApiResponse<Void> manualMatchJob(
            @PathVariable Long jobId,
            @RequestBody List<Long> workerIds,
            @RequestParam(required = false) String matchReason) {
        
        jobService.manualMatchJob(jobId, workerIds, matchReason);
        return ApiResponse.success("人工撮合完成", null);
    }

    /**
     * 获取合同管理列表
     */
    @GetMapping("/contracts")
    public ApiResponse<Page<ContractResponse>> getContracts(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) WorkContract.ContractStatus status) {
        
        Pageable pageable = PageRequest.of(page, size);
        Page<ContractResponse> contracts = contractService.getContractsForAdmin(pageable, status);
        return ApiResponse.success("", contracts);
    }

    /**
     * 强制更新合同状态
     */
    @PutMapping("/contracts/{contractId}/force-status")
    public ApiResponse<ContractResponse> forceUpdateContractStatus(
            @CurrentUser UserPrincipal currentUser,
            @PathVariable Long contractId,
            @RequestParam WorkContract.ContractStatus status,
            @RequestParam(required = false) String reason) {
        
        ContractResponse response = contractService.forceUpdateContractStatus(contractId, status, reason, currentUser.getId());
        return ApiResponse.success("", response);
    }

    /**
     * 获取结算管理列表（模拟数据）
     */
    @GetMapping("/settlements")
    public ApiResponse<Map<String, Object>> getSettlements(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        
        Map<String, Object> settlements = new HashMap<>();
        settlements.put("content", new ArrayList<>());
        settlements.put("totalElements", 0);
        settlements.put("totalPages", 0);
        settlements.put("size", size);
        settlements.put("number", page);
        settlements.put("message", "结算管理功能待实现");
        settlements.put("page", page);
        settlements.put("size", size);
        
        return ApiResponse.success("", settlements);
    }
    
    /**
     * 获取劳动者列表
     */
    @GetMapping("/workers")
    public ApiResponse<Map<String, Object>> getWorkers(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        
        Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());
        Page<WorkerProfile> workers = workerProfileRepository.findAllWithUser(pageable);
        
        List<WorkerProfileResponse> workerList = workers.getContent().stream()
            .map(WorkerProfileResponse::new)
            .collect(Collectors.toList());
        
        Map<String, Object> response = new HashMap<>();
        response.put("content", workerList);
        response.put("totalElements", workers.getTotalElements());
        response.put("totalPages", workers.getTotalPages());
        response.put("size", workers.getSize());
        response.put("number", workers.getNumber());
        
        return ApiResponse.success("", response);
    }

    /**
     * 获取劳动者详情
     */
    @GetMapping("/workers/{id}")
    public ApiResponse<WorkerProfileResponse> getWorkerById(@PathVariable Long id) {
        WorkerProfileResponse worker = workerProfileService.getWorkerById(id);
        return ApiResponse.success("", worker);
    }

    /**
     * 获取岗位详情
     */
    @GetMapping("/jobs/{jobId}")
    public ApiResponse<JobPostingResponse> getJobDetail(@PathVariable Long jobId) {
        JobPostingResponse job = jobService.getJobPostingById(jobId);
        return ApiResponse.success("", job);
    }

    /**
     * 删除岗位
     */
    @DeleteMapping("/jobs/{jobId}")
    public ApiResponse<Void> deleteJob(@PathVariable Long jobId) {
        jobService.deleteJob(jobId);
        return ApiResponse.success("岗位删除成功", null);
    }

    /**
     * 导出数据报表
     */
    @GetMapping("/reports/export")
    public ApiResponse<String> exportReport(
            @RequestParam String reportType,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        // 这里需要实现报表导出功能
        String exportUrl = "reports/" + reportType + "_" + System.currentTimeMillis() + ".xlsx";
        return ApiResponse.success(exportUrl);
    }

    /**
     * 系统配置管理
     */
    @GetMapping("/system/config")
    public ApiResponse<Map<String, Object>> getSystemConfig() {
        Map<String, Object> config = new HashMap<>();
        config.put("platformName", "招企人力外包平台");
        config.put("version", "1.0.0");
        config.put("maxFileSize", "10MB");
        config.put("supportedFileTypes", java.util.Arrays.asList("pdf", "jpg", "png", "doc", "docx"));
        return ApiResponse.success(config);
    }

    /**
     * 更新系统配置
     */
    @PutMapping("/system/config")
    public ApiResponse<Void> updateSystemConfig(
            @RequestBody Map<String, Object> config) {
        
        log.info("管理员更新系统配置: {}", config);
        // 这里需要实现系统配置更新逻辑
        return ApiResponse.success("系统配置更新成功", null);
    }
}
